<template>
  <demo-content :title="title">
    <p>
      Canvas
      绘图环境对象支持的全部基本图形包括：线段、矩形、圆形、圆弧及贝塞尔曲线。
      但是我们肯定需要再 canvas 中绘制除此以外的其他图形, 如三角形、六边形等。
    </p>
    <div class="tools">
      <stroke-color-selector v-model:value="strokeColor" />
      <fill-color-selector v-model:value="fillColor" />
      <div>
        <span>Sides:</span>
        <select v-model="sides">
          <option v-for="i of [4, 6, 8, 10, 12, 20]" :value="i">{{ i }}</option>
        </select>
      </div>
      <div>
        <span>Start angle:</span>
        <select v-model="startAngle">
          <option v-for="i of [0, 22.5, 45, 67.5, 90]" :value="i">
            {{ i }}
          </option>
        </select>
      </div>
      <div>
        <span>Fill</span>
        <input type="checkbox" v-model="fill" />
      </div>
      <div><button @click="initCtx">Erase all</button></div>
    </div>
    <canvas ref="canvasRef" width="800" height="600"></canvas>
  </demo-content>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { DrawingAssist, drawGrid, rect } from "./utils";
import { StrokeColorSelector, FillColorSelector } from "./components";

const title = "多边形绘制";
const strokeColor = ref("cornflowerblue");
const fillColor = ref("goldenrod");
const sides = ref(4);
const startAngle = ref(22.5);
const fill = ref(true);
// 指定组件上的属性
defineOptions({ title });

const canvasRef = ref<HTMLCanvasElement>();
let ctx: CanvasRenderingContext2D;
onMounted(() => {
  const canvas = canvasRef.value!;
  ctx = canvas.getContext("2d")!;
  initCtx();
  DrawingAssist.create(ctx)
    .setDrawingCallee((ctx, startPos, endPos) => {
      // 计算绘制半径
      const { x: x1, y: y1 } = startPos;
      const { x: x2, y: y2 } = endPos;
      const r = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
      const radian0 = (startAngle.value / 180) * Math.PI;
      const deltaRadian = (2 * Math.PI) / sides.value;
      ctx.save();
      ctx.beginPath();
      for (let i = 0; i < sides.value; ++i) {
        const radian = radian0 + i * deltaRadian;
        const x = x1 + r * Math.cos(radian);
        const y = y1 + r * Math.sin(radian);
        if (i) {
          ctx.lineTo(x, y);
        } else {
          ctx.moveTo(x, y);
        }
      }
      ctx.closePath();
      ctx.strokeStyle = strokeColor.value;
      ctx.stroke();
      if (fill.value) {
        ctx.fillStyle = fillColor.value;
        ctx.fill();
      }
      ctx.restore();
    })
    .useGuidewires({ type: "StartPos" });
});

function initCtx() {
  rect.clear(ctx);
  drawGrid(ctx, { stepx: 10, stepy: 10 });
}
</script>

<style src="./default.css" scoped></style>
